#define _GNU_SOURCE 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#include<unistd.h>
#include<poll.h>
#include<fcntl.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#define BUF_SIZE 64
int main(int argc,char* argv[])
{
if(argc<=2)
    {
        printf("usage: %s [ ip ] [ port ]\n",argv[0]);
    }
    int sock=socket(AF_INET,SOCK_STREAM,0);
    if(sock<0)
    {
        perror("socket\n");
        return 1;
    }
        struct sockaddr_in destaddr;
        destaddr.sin_port=htons(atoi(argv[2]));
        destaddr.sin_family=AF_INET;
        destaddr.sin_addr.s_addr=inet_addr(argv[1]); if(connect(sock,(struct sockaddr*)&destaddr,sizeof(destaddr))<0)
        //if(bind(sock,(struct sockaddr*)&server,sizeof(server))<0)
        {
            printf("connect\n ");
            close(sock);
            return 1;
             }
    struct   pollfd  fds[2];
        fds[0].fd=0;
        fds[0].events=POLLIN;
        fds[0].revents=0;        
        fds[1].fd=sock;
        fds[1].events=POLLIN | POLLRDHUP;
        fds[1].revents=0;
        char read_buf[BUF_SIZE];
        int pipefd[2];
        int ret= pipe(pipefd);
        assert(ret!=-1);
        while(1)
        {
            ret=poll(fds,2,-1);
            if(ret<0)
            {
                printf("poll\n");
                break;
            }
            if(fds[1].revents & POLLRDHUP)
            {
                printf("server close the connect\n");
                break;
            }
           // printf("please enter: ");
            else if(fds[1].revents & POLLIN)
            {
            printf("please enter: ");
                memset(read_buf,'\0',BUF_SIZE);
                recv(fds[1].fd,read_buf,BUF_SIZE-1,0);
                printf("%s\n",read_buf);
            }
            if(fds[0].revents & POLLIN)
            {
                ret=splice(0,NULL,pipefd[1],NULL,32768, SPLICE_F_MORE |SPLICE_F_MOVE);
                ret=splice(pipefd[0],NULL,sock,NULL,32768,SPLICE_F_MORE | SPLICE_F_MOVE);
            }
        }
 close(pipefd[0]);
 close(pipefd[1]);
    close(sock);
    return 0;
}
